package test.baojia.act.check;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.testng.Assert;

import java.util.*;

/**
 * 重复报价单检查。
 */
public class DuplicatedCheck extends Check {

    private final static String DIV_ID = "myModal5";

    @Override
    public void run(JSONObject context, WebDriver driver, Properties resource, JSONObject parentContext) throws  Exception  {
        super.run(context, driver, resource, parentContext);

        boolean dup = true;
        try{
            this.newWebDriverWait(null).until(
                    ExpectedConditions.visibilityOfElementLocated(By.id(DIV_ID))
            );
        }
        catch (Exception e){
            dup = false;
        }

        //判断重复报价单的提示内容。
        if(dup){
            final String jsScript = this.makeDefaultJsScript(new HashMap());
            List allRiskInForm = (List) this.newWebDriverWait(null).until(
                    ExpectedConditions.jsReturnsValue(jsScript)
            );
            //判断是否包含CAR。
            boolean hasCAR = allRiskInForm.contains("CAR");

            //如果有CAR，则需要对比项目名称。
            if(hasCAR){
                Assert.assertEquals(
                        driver.findElement(By.id("projectName")).getAttribute("value"),
                        driver.findElement(By.id("myModal5_projectName")).getAttribute("value"),
                        "The project Name not match."
                );
            }

            Assert.assertEquals(
                    driver.findElement(By.id("startDate")).getAttribute("value"),
                    driver.findElement(By.id("myModal5_startDate")).getAttribute("value"),
                    "The start date not match."
            );

            Assert.assertEquals(
                    driver.findElement(By.id("insuredName")).getAttribute("value"),
                    driver.findElement(By.id("myModal5_insuredName")).getAttribute("value"),
                    "The insured name not match."
            );

            //判断提示的险种和本报价单的险种是否有交集。
            List<String> risksPresented =
                    Arrays.asList(driver.findElement(By.id("myModal5_riskType")).getAttribute("value").split(","));
            Assert.assertTrue(
                    !CollectionUtils.intersection(risksPresented , allRiskInForm).isEmpty(),
                    "The risk intersection not exists."
            );

            driver.findElement(By.id("continuSaveBtn")).click();
            this.newWebDriverWait(null).until(
                    ExpectedConditions.invisibilityOfElementLocated(By.id(DIV_ID))
            );

        }
        else{
            //没有重复报价单，本用例测试通过。
            Assert.assertTrue(!dup);
        }
    }
}